#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
DEFAULT_ROOT_PATH = "/home/webadmin/echonews"
def speakText(text, **kwargs):
	import simplejson as json
	import subprocess
	from datetime import datetime
	from config import *
	verbose = kwargs.get('verbose', False)
	try: rootPath = JBOT_PATH
	except:	rootPath = DEFAULT_ROOT_PATH
	
	if kwargs.get('rootPath', False): rootPath = kwargs.get('rootPath')

	if text:
		text = text.encode('utf-8')
		date = datetime.today()
		fileName = 'speak/speak-%s-%s-%s-%s%s%s%s'%(date.year, date.month, date.day, date.hour, date.minute, date.second, date.microsecond)
		textFileName = rootPath+"/"+fileName
		#self.write('textfile: %s<br>'%textFileName)
		#self.write(u'text: %s'%text)
		textfile=open("%s.txt"%textFileName,"w")
		textfile.write(text)
		textfile.close()
		text2waveParams = (
		    "text2wave", "-f", "16000", "-eval", "(voice_msu_ru_nsh_clunits)", textFileName+".txt",
		    "-o", textFileName+".wav"
		)
		"""text2wave -f 44100 -eval '(voice_msu_ru_nsh_clunits)' "$1" -o "$1.wav" && mplayer "$1.wav"""
		if verbose: print "starting subprocess", " ".join(text2waveParams)
		p = subprocess.Popen(text2waveParams, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		if verbose: print "communicating.."
		output, errors = p.communicate()
		result = {'result': 'success', 'link': '', 'output': output, 'errors': errors, 'path': textFileName+".wav"}
		result['link'] = SITE_URL+"%s.wav"%fileName
		if errors:
		    result['result'] = 'error'
		if kwargs.get('asJson', True): return json.dumps(result)
		else: return result
	else: return False